package com.btpn.custody.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.btpn.custody.dao.IArea;
import com.btpn.custody.entity.Area;

@Repository("areaDaoHibernate")
public class AreaDAO implements IArea {

	protected HibernateTemplate template = null;
	
	@Autowired @Required
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	@Override
	public Area get(Long id) {
		return template.get(Area.class, id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Area> findAll() {
//		return template.loadAll(Area.class);
		return template.findByNamedQuery(Area.NQ__FIND__ALL);
	}
	
	@Override
	public Integer getCount() {
		return Integer.valueOf(findAll().size());
	}
	
	@Override
	public Serializable create(Area area) {
		return template.save(area);
	}

	@Override
	public void createOrUpdate(Area area) {
		template.saveOrUpdate(area);
	}

	@Override
	public void update(Area area) {
		template.update(area);
	}

	@Override
	public void delete(Long id) {
		template.delete(get(id));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Area getByName(String areaName) {
		List<Area> result = template.findByNamedQueryAndNamedParam(Area.NQ__FIND__BY__NAME, "areaName", areaName);
		
		if (result.size()>0) {
			return result.get(0);
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Area getByCode(String areaCode) {
		List<Area> result = template.findByNamedQueryAndNamedParam(Area.NQ__FIND__BY__CODE, "areaCode", areaCode);
		
		if (result.size()>0) {
			return result.get(0);
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Area> findInRegion(Long regionId) {

		return template.findByNamedQueryAndNamedParam(Area.NQ__FIND__IN_REGION, "regionId", regionId);
	}
}